package com.engine.cn.juc;

import lombok.Data;

/**
 * 5个哲学家5只筷子吃饭问题
 */
@Data
public class Philosopher extends Thread {
    //模拟左右筷子
    private final Chopstick left;
    private final Chopstick right;
    //模拟哲学家的序号
    private int index;

    public Philosopher(int index, Chopstick left, Chopstick right) {
        this.index = index;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        synchronized (left) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (right) {
                System.out.println(index + "号哲学家吃完了");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static void main(String[] args) {
        Chopstick c0 = new Chopstick("c0");
        Chopstick c1 = new Chopstick("c1");
        Chopstick c2 = new Chopstick("c2");
        Chopstick c3 = new Chopstick("c3");
        Chopstick c4 = new Chopstick("c4");

        //注意这里的顺序问题,在调用的时候给他顺序就行了。加入了两个左撇子解决了问题
        Philosopher p0 = new Philosopher(0, c0, c1);
        //Philosopher p1 = new Philosopher(1, c1, c2);
        Philosopher p1 = new Philosopher(1, c2, c1);
        Philosopher p2 = new Philosopher(2, c2, c3);
        // Philosopher p3 = new Philosopher(3, c3, c4);
        Philosopher p3 = new Philosopher(3, c4, c3);
        Philosopher p4 = new Philosopher(4, c4, c0);
        p0.start();
        p1.start();
        p2.start();
        p3.start();
        p4.start();
    }

}
